package com.yuncheng.spcyApi.scheduleJob;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.YpscFlowConstant;
import com.yuncheng.spcyApi.constant.jcy.JcyLxjhConstant;
import com.yuncheng.spcyApi.constant.schedule.ScheduleConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.selectXzxkApi.api.XzspJkApi;
import com.yuncheng.spcyApi.partyService.PartyHyService;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.mapper.SpcyFlowMapper;
import com.yuncheng.spcyApi.selectXzxkApi.service.PutZwxtService;
import com.yuncheng.spcyApi.selectXzxkApi.vo.XzspJkApiSlxxVo;
import com.yuncheng.spcyApi.selectXzxkApi.vo.XzspJkApiSpcyjlVo;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.spcyService.XpryTimedTasksService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.spcy.SpcyFlowVo;
import com.yuncheng.spcyApi.vo.wj.WjjlVo;
import groovy.util.logging.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;
import utils.WorkDateUtils;

import javax.annotation.Resource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 审评查验 -- 定时任务-执行任务方法bean
 */
@Slf4j
@Component("spcyScheduleTask")
public class SpcyScheduleTask {
    private static final Logger log = LoggerFactory.getLogger(SpcyScheduleTask.class);

    @Resource
    private XzspJkApi xzspJkApi;

    @Resource
    private ISpcyScheduleJobBasicService spcyScheduleJobBasicService;

    @Resource
    @Lazy
    private ISpcySmsLogService spcySmsLogService;

    @Resource
    private ScheduleJobService scheduleJobService;

    @Resource
    private SpcyFlowMapper spcyFlowMapper;

    @Resource
    @Lazy
    private ISpcyScheduleJobLogService spcyScheduleJobLogService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    private BusinessConstant businessConstant;

    @Resource
    @Lazy
    private PutZwxtService putZwxtService;

    @Resource
    @Lazy
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    @Lazy
    private PartyHyService partyHyService;

    @Resource
    @Lazy
    private ISpcyPxJbxxService spcyPxJbxxService;

    @Resource
    @Lazy
    private XpryTimedTasksService xpryTimedTasksService;

    @Resource
    @Lazy
    private ISpcyRsJjrkService spcyRsJjrkService;


    /**
     * 获取行政审批数据 - 定时任务
     */
    public void getXzspData(){
        SpcyRsJlxcrwsj timeStamp = xzspJkApi.getTimeStamp();
        log.info("当前时间: {}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        log.info("获取行政审批数据-执行定时时间-{}", timeStamp.getFsjc());

        // 记录定时任务记录
        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.rw_name_getXzspData_Method);
        jobBasic.setFrwmc(ScheduleConstant.rw_name_getXzspData); // 任务名称
        jobBasic.setFzxsj(timeStamp.getFsjc());
        spcyScheduleJobBasicService.save(jobBasic);

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        xzspJkApi.tqSqsx(timeStamp.getFsjc(),null,currentUser,jobBasic,null); // 获取数据

        // 更新定时任务记录结束时间
        SpcyScheduleJobBasic newJobBasic = spcyScheduleJobBasicService.getById(jobBasic.getId());

        if (newJobBasic != null && StringUtils.isBlank(newJobBasic.getFzxzt())) {
            jobBasic.setFjssj(new Date());
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
        }

        List<SpcyScheduleJobLog> logList = spcyScheduleJobLogService.list(new LambdaQueryWrapper<SpcyScheduleJobLog>()
                .eq(SpcyScheduleJobLog::getFzxrwid, jobBasic.getId()));
        if (CollectionUtils.isNotEmpty(logList)){
            String logNr = "";
            for (SpcyScheduleJobLog log : logList){
                logNr += log.getFzxnr() + "\n";
            }
            jobBasic.setFzxqk(logNr);
        }
        spcyScheduleJobBasicService.updateById(jobBasic);

        log.info("获取审评中心数据-end executeAsync-{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    /**
     * 行政审批数据-推送任务受理信息
     * @param params 申请事项id
     */
    public void pushXzspDataByRwsl(String params){
        StringBuffer msg = new StringBuffer();
        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.Xzsp_Data_Rwsl_Method);
        jobBasic.setFrwmc(ScheduleConstant.Xzsp_Data_Rwsl_Name); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));

        if (StringUtils.isBlank(params)){
            log.error("定时任务-行政审批数据-推送任务受理信息【失败】：【申请事项id】参数为空");
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk(msg.toString());
            jobBasic.setFzxqk(msg.toString());
            jobBasic.setFjssj(new Date());
            spcyScheduleJobBasicService.save(jobBasic);
            return;
        }

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(params);
        if (sqsx == null){
            log.error("定时任务-行政审批数据-推送任务受理信息【失败】：【申请事项】为空, 参数为{}",params);
            msg.append("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项】为空, 参数为"+params);
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk(msg.toString());
            jobBasic.setFzxqk(msg.toString());
            jobBasic.setFjssj(new Date());
            spcyScheduleJobBasicService.save(jobBasic);
            return;
        }

        String blr = ""; // 办理人
        String blyj = "同意受理。"; // 办理意见
        String sczt = "1"; // 审查状态 1；受理，2不受理

        // 获取任务受理 环节流程
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsx.getId())
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_RWSL)
                .orderByAsc(SpcySqsxJob::getFfssj));
        if (CollectionUtils.isNotEmpty(jobList)){
            blr = jobList.get(0).getFblr();
        }

        XzspJkApiSlxxVo slxxVo = new XzspJkApiSlxxVo();
        slxxVo.setSxsqjbxx_id(sqsx.getFsxsqjbxxid());
        slxxVo.setSlbyslr(blr);
        slxxVo.setSlbyslyj(blyj);
        slxxVo.setSlbyslsj(sqsx.getFslsj());
        slxxVo.setSczt(sczt);

        if (StringUtils.isBlank(sqsx.getFxzspzt()) || !sqsx.getFxzspzt().equals(SpcyConstant.SQSX_BASIC_XZSPZT_YES)) {
            return;
        }

        msg.append("【申请事项id】为[").append(sqsx.getId()).append("]；");
        msg.append("【受理不予受理】为[").append(blr).append("]；");
        msg.append("【受理不予受理意见】为[").append(blyj).append("]；");
        msg.append("【受理不予受理时间】为[").append(sqsx.getFslsj()).append("]；");
        msg.append("【受理状态】为[").append(sqsx.getFslzt()).append("]；");
        msg.append("【办理人】为[").append(blr).append("]；");
        msg.append("【办理意见】为[").append(blyj).append("]；");

        jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
        jobBasic.setFzxqk(msg.toString());
        jobBasic.setFjssj(new Date());

        // 属于行政审评数据推送
        xzspJkApi.tsSlxx(slxxVo, jobBasic);
    }

    /**
     * 行政审批数据-推送审查结论信息
     * @param params 申请事项id
     */
    public void pushXzspDataByScjl(String params){
        StringBuffer msg = new StringBuffer();
        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.Xzsp_Data_Scjl_Method);
        jobBasic.setFrwmc(ScheduleConstant.Xzsp_Data_Scjl_Name); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));

        if (StringUtils.isBlank(params)){
            log.error("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项id】参数为空");
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk(msg.toString());
            jobBasic.setFzxqk(msg.toString());
            jobBasic.setFjssj(new Date());
            jobBasic.setCreateTime(new Date());
            spcyScheduleJobBasicService.save(jobBasic);
            return;
        }

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(params);
        if (sqsx == null){
            log.error("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项】为空, 参数为{}",params);
            msg.append("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项】为空, 参数为"+params);
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk(msg.toString());
            jobBasic.setFzxqk(msg.toString());
            jobBasic.setFjssj(new Date());
            jobBasic.setCreateTime(new Date());
            spcyScheduleJobBasicService.save(jobBasic);
            return;
        }

        String ywbmjbrid = ""; // 业务部门经办人id
        String scjlysr = "蒋受军"; // 审查结论移送人
        String scjy = "审查完成。"; // 审查结论

        if (StringUtils.isNotBlank(sqsx.getFxzspysrid())){
            /*String[] ysrid = sqsx.getFxzspysrid().split("#");
            ywbmjbrid = ysrid[0];*/
            ywbmjbrid = sqsx.getFxzspysrid();
        }

        // 移送确认 环节流程
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsx.getId())
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_YSQR)
                .orderByDesc(SpcySqsxJob::getFfssj));
        if (CollectionUtils.isNotEmpty(jobList)){
            if (StringUtils.isNotBlank(jobList.get(0).getFblr())) {
                scjlysr = jobList.get(0).getFblr();
            }

            if (StringUtils.isNotBlank(jobList.get(0).getFblyj())) {
                scjy = jobList.get(0).getFblyj();
            }
        }

        // 记录内容
        msg.append("【申请事项id】为[").append(sqsx.getId()).append("]；");
        msg.append("【审查结论】为[").append(scjy).append("]；");
        msg.append("【审查结论移送人】为[").append(scjlysr).append("]；");
        msg.append("【业务部门经办人ID】为[").append(ywbmjbrid).append("]；");

        jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
        jobBasic.setFycqk(msg.toString());
        jobBasic.setFzxqk(msg.toString());
        jobBasic.setFjssj(new Date());

        /** 推送审查结论 */
        XzspJkApiSpcyjlVo xzspJkApiSpcyjlVo = new XzspJkApiSpcyjlVo();
        xzspJkApiSpcyjlVo.setSxsqjbxx_id(sqsx.getFsxsqjbxxid());
        xzspJkApiSpcyjlVo.setYwbmjbrid(ywbmjbrid);
        xzspJkApiSpcyjlVo.setScjlydr(scjlysr);
        xzspJkApiSpcyjlVo.setScjl(scjy);
        xzspJkApi.tsSpcyjl(xzspJkApiSpcyjlVo, jobBasic);

    }

    /**
     * 行政审批数据-推送材料附件信息
     * @param params 申请事项id
     */
    public void pushXzspDataByClfj(String params){
        StringBuffer msg = new StringBuffer();
        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.Xzsp_Data_Fjcl_Code_Method);
        jobBasic.setFrwmc(ScheduleConstant.Xzsp_Data_Fjcl_Name); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));

        if (StringUtils.isBlank(params)){
            log.error("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项id】参数为空");
            msg.append("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项id】参数为空");
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk(msg.toString());
            jobBasic.setFzxqk(msg.toString());
            jobBasic.setFjssj(new Date());
            spcyScheduleJobBasicService.save(jobBasic);
            return;
        }

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(params);
        if (sqsx == null){
            log.error("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项】为空, 参数为{}",params);
            msg.append("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项】为空, 参数为"+params);
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk(msg.toString());
            jobBasic.setFzxqk(msg.toString());
            jobBasic.setFjssj(new Date());
            spcyScheduleJobBasicService.save(jobBasic);
            return;
        }

        msg.append("【申请事项id】为[").append(sqsx.getId()).append("]；");

        /** 推送附件 */

        // 获取申请事项文件记录
        /*WjjlVo wjjlVo = new WjjlVo();
        wjjlVo.setFpid(sqsx.getId());
        if (StringUtils.isBlank(sqsx.getFywflcode())) {
            wjjlVo.setFywflcode(SpcyConstant.YWFL_CODE_YPSC);
        }else {
            wjjlVo.setFywflcode(sqsx.getFywflcode());
        }
        List<WjjlVo> wjjlList = spcySqsxWjjlService.findWjjlList(wjjlVo);*/

        List<WjjlVo> wjjlList = spcySqsxWjjlService.findBtWjjlList(sqsx.getId(),
                sqsx.getFywflcode(),
                null,
                SpcyCommonConstant.SQSX_WJML_TYPE2_TSZW);
        msg.append("【文件总数量】:").append(wjjlList.size()).append("。");
        if (CollectionUtils.isNotEmpty(wjjlList)){

            // 推送不为 报账材料
            /*List<WjjlVo> xcjcclList = wjjlList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getClml())
                            && !f.getClml().equals(WjmlConstant.wjml_type_3_bzcl) && StringUtils.isBlank(f.getFwjlx5()))
                    .collect(Collectors.toList());*/

            // 技术审评材料
            /*List<WjjlVo> jsspclList = wjjlList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getClml())
                            && f.getClml().equals(WjmlConstant.wjml_type_4_jsspcl) && StringUtils.isBlank(f.getFwjlx5()))
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(jsspclList)) {
                xcjcclList.addAll(jsspclList);
            }*/

            msg.append("【推送材料文件数量】:").append(wjjlList.size()).append("。");

            // 推送材料
//            if (CollectionUtils.isNotEmpty(xcjcclList)){

                List<String> updateTsZtIdList = new ArrayList<>();

                for (WjjlVo wj : wjjlList){
                    if (StringUtils.isBlank(wj.getFcflj())){
                        continue;
                    }

                    if (StringUtils.isNotBlank(wj.getFwjlx5()) && wj.getFwjlx5().equals(SpcyCommonConstant.SQSX_WJJL_TYPE5_SFYTS_YTS)){
                        continue;
                    }

                    String path = "";
                    try {
                        if (localFileUploadUtils.isEnableMinioWjjlFile()){
                            File file = localFileUploadUtils.convertMinioToFile(localFileUploadUtils.getSqsxWjjlRelativeUrl(wj.getFcflj()), "");
                            if (file != null){
                                path = file.getAbsolutePath();
                            }
                        }else {
                            path = localFileUploadUtils.getSqsxWjjlAbsUrl(wj.getFcflj());
                        }

                        HttpResult httpResult = xzspJkApi.tsJccl(new File(path), wj.getFwjxsmc() + wj.getFwjlx(), sqsx.getFsxsqjbxxid(), wj.getCreateBy());
                        if (httpResult.isSuccess()) {
                            updateTsZtIdList.add(wj.getId());
                        }

                        msg.append(httpResult.getMessage());

                    }catch (Exception e){
                        msg.append("【error 文件id:"+wj.getId()+"】");
                    }

                }

                spcySqsxWjjlService.updateWjjlByWjlx5(updateTsZtIdList);
//            }
        }

        jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
        jobBasic.setFycqk(msg.toString());
        jobBasic.setFzxqk(msg.toString());
        jobBasic.setFjssj(new Date());
        jobBasic.setCreateTime(new Date());
        spcyScheduleJobBasicService.save(jobBasic);
    }

    /**
     * 行政审批数据 - 推送审评流转办理意见接口
     */
    public void pushSpJobLzjl(String params){
        StringBuffer msg = new StringBuffer();

        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.Xzsp_Data_Lzjl_Method);
        jobBasic.setFrwmc(ScheduleConstant.Xzsp_Data_Lzjl_Name); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));

        if (StringUtils.isBlank(params)){
            log.error("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项id】参数为空");
            msg.append("定时任务-行政审批数据-推送审查结论信息【失败】：【申请事项id】参数为空");
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk(msg.toString());
            jobBasic.setFzxqk(msg.toString());
            jobBasic.setFjssj(new Date());
            spcyScheduleJobBasicService.save(jobBasic);
            return;
        }
        putZwxtService.pushSpJobLzjl(params);
    }

    /**
     * 定时任务 - 计算申请事项-从受理到移送之间的天数
     */
    public void computeSqsxAcceptedDays(){
        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.Xzsp_Data_Computed_Slts_Code_Method);
        jobBasic.setFrwmc(ScheduleConstant.Xzsp_Data_Computed_Slts_Name); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));

        // 未移送的申请事项
        List<SpcySqsxBasic> sqsxList = spcySqsxBaiscService.list(new LambdaQueryWrapper<SpcySqsxBasic>()
                .and(wq -> wq.isNull(SpcySqsxBasic::getFlczt)
                        .or()
                        .ne(SpcySqsxBasic::getFlczt, SpcyConstant.LCZT_LCJS)
                ));
        int count = 0; // 更新总数
        StringBuffer msg = new StringBuffer();
        if (CollectionUtils.isNotEmpty(sqsxList)){
        }
        msg.append("一共计算总数：");
        msg.append(count).append("。\n");
        jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
        jobBasic.setFzxqk(msg.toString());
        jobBasic.setFjssj(new Date());
        spcyScheduleJobBasicService.save(jobBasic);

    }

    /**
     * 定时任务 - 监听申请事项 - 环节待办 - 是否超时 - 同一天发送预警
     */
    public void watchSqsxJobNodeSfcs(){

        // 审评查验 - 流程
        SpcyFlowVo spcyFlowVo = new SpcyFlowVo();
        spcyFlowVo.setFblzt(SpcyConstant.BLZT_DB);
        spcyFlowVo.setFlcmc(YpscFlowConstant.LCMC_LIKE_SPCYLC);
        List<SpcyFlowVo> jobList = spcyFlowMapper.flowJkList(false, null, spcyFlowVo);
        if (CollectionUtils.isNotEmpty(jobList)){
            for (SpcyFlowVo job : jobList){
                if (job.getFjzblts() != 0 && job.getFjzblsj() != null) {
                    // 是否同一天
                    boolean isSameDay = DateConversionUtils.DateToStringYYYYMMDD(new Date()).equals(DateConversionUtils.DateToStringYYYYMMDD(job.getFjzblsj()));
                    if (isSameDay) {
                        // 待完善
                    }
                }
            }
        }

    }

    public void taskByParams(String params) {
        log.info("taskByParams执行时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        log.info("taskByParams执行有参示例任务：{}",params);
    }

    public void taskNoParams() {
        log.info("taskByParams执行时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        log.info("taskNoParams执行无参示例任务");
    }

    public void test(String params) {
        log.info("test执行时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        log.info("test执行有参示例任务：{}",params);
    }

    /**
     * 定时任务-发送短信
     */
    public void smsScheduleJob(String params){

        if (StringUtils.isBlank(params)){
            log.error("定时任务-发送短信-失败，主要参数为空");
            return;
        }
        SpcySmsLog smsLog = spcySmsLogService.getById(params);
        if (smsLog == null){
            log.error("定时任务-发送短信-失败，记录不存在：{}",params);
            return;
        }
        // 记录定时任务记录
        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.Schedule_Task_SMS);

        StringBuffer str = new StringBuffer("定时任务-发送短信：");
        str.append("\n").append("[接收对象]").append("为").append("【").append(smsLog.getFjsdx()).append("】");
        str.append("\n").append("[自定义对象]").append("为").append("【").append(smsLog.getFzdydx()).append("】");
        str.append("\n").append("[短信内容]").append("为").append("【").append(smsLog.getFdxnr()).append("】");
        str.append("\n").append("[发送人]").append("为").append("【").append(smsLog.getFusername()).append("】");

        jobBasic.setFrwmc(str.toString()); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));
        spcyScheduleJobBasicService.save(jobBasic);

        scheduleJobService.sendSmsWithSchedule(smsLog); // 发送短信

        // 更新定时任务记录结束时间
        jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
        jobBasic.setFjssj(new Date());
        jobBasic.setFzxqk(str.toString());
        spcyScheduleJobBasicService.updateById(jobBasic);
    }

    /**
     * 定时任务-删除所有的临时文件 （test/temp下所有临时文件）凌晨2点
     */
    public void deleteTempFile(){

        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod("deleteTempFile");
        jobBasic.setFrwmc("定时任务-删除所有的临时文件"); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));
        jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
        jobBasic.setFycqk("0");
        jobBasic.setFzxqk("定时任务-删除所有的临时文件-"+DateConversionUtils.DateToYMDHMSChineseString(new Date()));
        jobBasic.setFjssj(new Date());
        spcyScheduleJobBasicService.save(jobBasic);

        // 临时文件-文件夹
        String baseDirUrl = localFileUploadUtils.getTempFileRootUrl();
        File dir = new File(baseDirUrl);
        if (dir.exists()) {
            LocalFileUploadUtils.deleteDirFile(dir);
        }
    }

    /**
     * 定时任务-删除已经移送的申请事项在本地生成的文件
     */
    public void deleteSqsxLocalWjjl(String params){
        boolean isFlag = true;

        SpcyScheduleJobBasic jobBasic = new SpcyScheduleJobBasic();
        jobBasic.setId(GetUuIdUtils.NotReplaceUuId());
        jobBasic.setFmethod(ScheduleConstant.Delete_Sqsx_Local_Wjjl_Method);
        jobBasic.setFrwmc(ScheduleConstant.Delete_Sqsx_Local_Wjjl_Name); // 任务名称
        jobBasic.setFzxsj(DateConversionUtils.DateToDays(new Date()));

        if (StringUtils.isBlank(params)){
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
        }else {
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Success);
            jobBasic.setFycqk("0");
        }

        if (!businessConstant.IS_ENABLE_WJJL_MINIO){
            isFlag = false;
            jobBasic.setFzxzt(ScheduleConstant.Job_Basic_Error);
            jobBasic.setFycqk("未启用minio存储，无需删除本地文件！");
        }

        jobBasic.setFzxqk("定时任务-删除已经移送的申请事项在本地生成的文件-"+DateConversionUtils.DateToYMDHMSChineseString(new Date()));
        jobBasic.setFjssj(new Date());
        spcyScheduleJobBasicService.save(jobBasic);

        if (!isFlag){
            return;
        }

        StringBuffer zxqk = new StringBuffer();
        // 文件记录
        List<SpcySqsxWjjl> wjjlList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFpid, params)
                .isNull(SpcySqsxWjjl::getFwjlx5)
                .orderByAsc(SpcySqsxWjjl::getCreateTime));
        if (CollectionUtils.isNotEmpty(wjjlList) && businessConstant.IS_ENABLE_WJJL_MINIO){
            for (SpcySqsxWjjl wjjl : wjjlList) {
                if (StringUtils.isNotEmpty(wjjl.getFcflj())) {
                    zxqk.append(wjjl.getFwjxsmc()+wjjl.getFwjlx()).append("\n");
                    localFileUploadUtils.deleteLocalFileUrl(wjjl.getFcflj(),false);
                }
                if (StringUtils.isNotEmpty(wjjl.getFjdcflj())){
                    zxqk.append(wjjl.getFwjxsmc()+wjjl.getFwjlx()).append("\n");
                    localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj(),false);
                }
            }
        }
        jobBasic.setFzxqk(zxqk.toString());
        spcyScheduleJobBasicService.updateById(jobBasic);
    }

    /**
     * 定时任务-预警整改通知
     */
    public void yjZgNotice(){
        List<SpcySqsxBczgjl> noZgwcSqsxList = putZwxtService.getNoZgwcSqsxList();
        if (CollectionUtils.isNotEmpty(noZgwcSqsxList)){
            for (SpcySqsxBczgjl bczgjl : noZgwcSqsxList){
                if (StringUtils.isNotBlank(bczgjl.getFzgsx()) && bczgjl.getFjzrq() != null) {
                    boolean isSameDay = DateConversionUtils.DateToStringYYYYMMDD(new Date()).equals(DateConversionUtils.DateToStringYYYYMMDD(bczgjl.getFjzrq()));
                    if (isSameDay){
                        StringBuffer msg = new StringBuffer();
                        if (StringUtils.isNotBlank(bczgjl.getFfqr())) {
                            msg.append(bczgjl.getFfqr());
                        }
                        msg.append("在");
                        if (bczgjl.getFfqrq() != null){
                            msg.append(DateConversionUtils.DateToYMDHMSChineseString(bczgjl.getFfqrq()));
                        }
                        msg.append("发起的整改还未完成！");

                        putZwxtService.sendSmsToZbrHzKzfzr(null,bczgjl.getFsqsxid(),msg.toString());
                    }
                }
            }
        }
    }

    /**
     * 定时任务-预警补齐补正通知
     */
    public void yjBqbzNotice(){
        List<SpcySqsxBqbzjl> noBqbzwcSqsxList = putZwxtService.getNoBqbzwcSqsxList();
        if (CollectionUtils.isNotEmpty(noBqbzwcSqsxList)){
            for (SpcySqsxBqbzjl bqbzjl : noBqbzwcSqsxList){
                if (StringUtils.isNotBlank(bqbzjl.getFbqbzsx()) && bqbzjl.getFjzrq() != null) {
                    boolean isSameDay = DateConversionUtils.DateToStringYYYYMMDD(new Date()).equals(DateConversionUtils.DateToStringYYYYMMDD(bqbzjl.getFjzrq()));
                    if (isSameDay){
                        StringBuffer msg = new StringBuffer();
                        if (StringUtils.isNotBlank(bqbzjl.getFfqr())) {
                            msg.append(bqbzjl.getFfqr());
                        }
                        msg.append("在");
                        if (bqbzjl.getFfqrq() != null){
                            msg.append(DateConversionUtils.DateToYMDHMSChineseString(bqbzjl.getFfqrq()));
                        }
                        msg.append("发起的补齐补正还未完成！");

                        putZwxtService.sendSmsToZbrHzKzfzr(null,bqbzjl.getFsqsxid(),msg.toString());
                    }
                }
            }
        }
    }

    /**
     * 定时任务-审评查验流程-申请事项-预警通知
     */
    public void yjSpcyFlowSqsxNotice(){
        // 没有办结的申请事项,存在完成时限
        List<SpcySqsxBasic> sqsxList = spcySqsxBaiscService.list(new LambdaQueryWrapper<SpcySqsxBasic>()
                .isNull(SpcySqsxBasic::getFlczt)
                .isNotNull(SpcySqsxBasic::getFjzrq)
                .ne(SpcySqsxBasic::getFwcsx,0));

        if (CollectionUtils.isEmpty(sqsxList)){
            return;
        }

        for (SpcySqsxBasic sqsx : sqsxList) {
            int days = DateConversionUtils.differentDays(new Date(), sqsx.getFjzrq());
            if (days >= 0 && days <= 7 ) {
                // 判断同一天
                boolean isSameDay = DateConversionUtils.DateToStringYYYYMMDD(new Date()).equals(DateConversionUtils.DateToStringYYYYMMDD(sqsx.getFjzrq()));
                if (isSameDay) {
                    StringBuffer msg = new StringBuffer();
                    msg.append("总办理时限为最后一天！请及时前往系统[ ");

                    msg.append(SpcyConstant.System_Name).append(" -> ").append(SpcyConstant.System_Url).append(" ]查看，进行办理。");
                    putZwxtService.sendSmsToZbrHzKzfzr(sqsx, null, msg.toString());
                }else {
                    StringBuffer msg = new StringBuffer();
                    msg.append("总办理时限剩余（").append(days).append("）天，");
                    msg.append("请及时前往系统[ ");
                    msg.append(SpcyConstant.System_Name).append(" -> ").append(SpcyConstant.System_Url).append(" ]查看，进行办理。");
                    putZwxtService.sendSmsToZbrHzKzfzr(sqsx, null, msg.toString());
                }

            }else if (days < 0){
                StringBuffer msg = new StringBuffer();
                msg.append("办理截止日期为（").append(DateConversionUtils.DateToYMDHMSChineseString(sqsx.getFjzrq())).append("），");
                msg.append("总办理时限超时（").append(days).append("）天，");
                msg.append(SpcyConstant.System_Name).append(" -> ").append(SpcyConstant.System_Url).append(" ]查看，进行办理。");
                putZwxtService.sendSmsToZbrHzKzfzr(sqsx, null, msg.toString());
            }
        }
    }

    /**
     * 定时任务-党务会议计划
     */
    public void syncDwhyjh(String params){
        partyHyService.syncHyjl(null, params);
    }

    /**
     * 定时任务-遴选培训计划-计算报名截止日期(报名状态) 0 30 0 * * ? (凌晨 00：30)
     */
    public void syncJcyLxjhBmzt(){
        List<SpcyPxJbxx> list = spcyPxJbxxService.list(new LambdaQueryWrapper<SpcyPxJbxx>()
                .eq(SpcyPxJbxx::getFpxlx, JcyLxjhConstant.JCYLX_PXLX_XJCYPX)
                .isNotNull(SpcyPxJbxx::getFjhjzsj)
                .ne(SpcyPxJbxx::getFjhzt, JcyLxjhConstant.LX_JHZT_JHWC));

        if (CollectionUtil.isEmpty(list)){
            return;
        }

        String nowDate = DateConversionUtils.DateToStringYYYYMMDD(new Date());
        for (SpcyPxJbxx lx : list){
            if (StringUtils.isNotBlank(lx.getFjhjzsj())){
                if (lx.getFjhjzsj().compareTo(nowDate) < 0){
                    lx.setFpxbmzt(JcyLxjhConstant.JCYLX_PXZT_WKS);
                    spcyPxJbxxService.updateById(lx);
                }
            }
        }

    }

    /**
     * 定时任务-申请事项自动选派人员
     * @param params
     */
    public void sqsxAutoXpry(String params){
        Date nowDate = new Date();

        boolean isXzsj = false; // 是否为行政时间
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            Date nowTime = sdf.parse(new SimpleDateFormat("HH:mm:ss").format(nowDate));

            // 上午范围开始时间
            Date startTimeO1 = sdf.parse("07:55:00");
            Date endTimeO1 = sdf.parse("12:05:00");

            // 下午范围结束时间
            Date startTimeO2 = sdf.parse("15:00:00");
            Date endTimeO2 = sdf.parse("20:00:00");

            // 验证当前是上午还是下午
            if (DateUtil.isIn(nowTime, startTimeO1, endTimeO1)){
                isXzsj = true; // 上午
            }
            else if (DateUtil.isIn(nowTime, startTimeO2, endTimeO2)){
                isXzsj = true; // 下午
            }
        } catch (ParseException e) {
            log.error("[ParseException]定时任务-申请事项自动选派人员: {}", e.getMessage());
        }

        // 当前非行政时间结束
        if (!isXzsj){
            return;
        }

        if (WorkDateUtils.getWeekOfDate(nowDate)){
            // 周一到周五
            boolean isTx = spcyRsJjrkService.verifyNowDateIsTx(nowDate); // 是否调休
            if (isTx){
                // 调休不执行
            }else {
                xpryTimedTasksService.timedTasksAutoXpryYwxx(params, null);
            }
        }else {
            // 周末
            boolean isJb = spcyRsJjrkService.verifyNowDateIsJb(nowDate); // 是否加班
            if (isJb){
                xpryTimedTasksService.timedTasksAutoXpryYwxx(params, null);
            }
        }
    }

    /**
     * 定时任务-发送选派人员短信过期确认
     * @param params
     */
    public void expireXpryQrSms(String params){
        xpryTimedTasksService.expireXpryQrSms(params);
    }

}
